<template>
    <!--物资验收修改 -->
    <div class="e-form">
        <BillTop title="周材验收详情" @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs" v-if="Object.keys(formData).length != 0">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <!-- 基本信息 -->
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="验收明细"
                    name="receivingMaterials"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="服务费用"
                    name="serviceCharge"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="附件信息"
                    name="accessory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfoCon" class="con">
                        <div class="e-form">
                            <div class="tabs">
                                <div class="tabs-title" id="baseInfo">
                                    基本信息
                                </div>
                                <div style="width: 100%" class="form">
                                    <el-form
                                        :model="formData"
                                        label-width="150px"
                                        :rules="formDataRules"
                                        ref="formDataRef"
                                    >
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="验收编号">
                                                    {{ formData.billNo }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="机构">
                                                    {{ formData.orgName }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="业务类型"
                                                    prop="businessTypeKey"
                                                >
                                                   {{formData.businessTypeValue}}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="源单编号" :prop="formData.businessTypeKey !== '6' ? 'sourceNo' : 'sourceNos'">
                                                    <span>
                                                        {{formData.sourceNo}}
                                                        <i
                                                            slot="suffix"
                                                            class="
                                                                el-input__icon
                                                                el-icon-document-copy
                                                            "
                                                            @click="
                                                                sourceNoClick
                                                            "
                                                            v-show="formData.businessTypeKey !== '6'"
                                                        ></i>
                                                    </span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="供方"
                                                    prop="supplierName"
                                                >
                                                   {{formData.supplierName}}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="采购人员"
                                                    prop="purchaserName"
                                                >
                                                    {{ formData.purchaserName }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <!-- 汇总验收明细金额+进场费 -->
                                                <el-form-item
                                                    label="验收金额(元)"
                                                    prop="acceptanceAmount"
                                                >
                                                    {{
                                                        formData.acceptanceAmount
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="验收人员">
                                                    {{
                                                        formData.acceptancerName
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <!-- 汇总服务费用明细金额,可为0 -->
                                                <el-form-item
                                                    label="服务费用(元)"
                                                    prop='transportationCost'
                                                >
                                                    {{
                                                        formData.transportationCost
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="验收日期"
                                                    prop="acceptanceDate"
                                                >
                                                    {{formData.acceptanceDate}}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="验结一体"
                                                    :prop="
                                                        formData.isAccepSettle
                                                            ? 'invoiceNo'
                                                            : 'invoiceNos'
                                                    "
                                                >
                                                    <el-checkbox
                                                        v-model="
                                                            formData.isAccepSettle
                                                        "
                                                        label=""
                                                        style="
                                                            margin-right: 10px;
                                                        "
                                                        disabled
                                                    ></el-checkbox>
                                                    <span>发票编号:{{formData.invoiceNo}}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="税率%"
                                                    prop="taxRate"
                                                >
                                                   {{formData.taxRate}}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="税额"
                                                    prop="taxAmount"
                                                >
                                                    {{formData.taxAmount}}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12" prop='totalPriceAndTax'>
                                                <el-form-item label="税价合计">
                                                    {{
                                                        formData.totalPriceAndTax
                                                    }}元
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="币种"
                                                    prop="currencyId"
                                                >
                                                   {{formData.currency}}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="本位币"
                                                    prop="baseCurName"
                                                >
                                                    {{ formData.baseCurName }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>

                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="本位币汇率"
                                                    prop="baseCurExchangeRate"
                                                >
                                                   {{formData.baseCurExchangeRate}}
                                                </el-form-item>
                                            </el-col>
                                            <!-- <el-col :span="12">
                                                <el-form-item
                                                    label="验收金额(本位币)"
                                                >
                                                    {{
                                                        formData.baseAcceptanceAmount
                                                    }}
                                                </el-form-item>
                                            </el-col> -->
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <!-- 只有内租 外租才显示该字段 -->
                                                <!-- <el-form-item
                                label="进场费(元)"
                                prop="approachCost"
                            >
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.approachCost"
                                    v-enterFloat2
                                    @blur="approachCostBlur"
                                ></el-input>
                            </el-form-item> -->
                                            </el-col>
                                        </el-row>

                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="传财务共享"
                                                >
                                                    {{ formData.easId ? '已传' : '未传'}}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="结算编号" v-show='formData.settleNo'>
                                                    <span style="color: blue;cursor: pointer;" @click='settlementNoClick'>{{formData.settleNo}}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-form-item label="备注">
                                               {{formData.remarks}}
                                            </el-form-item>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="状态">
                                                    {{
                                                        showState(
                                                            formData.state
                                                        )
                                                    }}
                                                    <!-- 草稿/审核中/已审核/已关闭/已作废 -->
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12" v-if="formData.redBillState !== -1">
                                                <el-form-item label="冲红单"
                                                    ><span
                                                        :style="
                                                            redBillStateStyle
                                                        "
                                                        >{{
                                                            redBillStateFun
                                                        }}</span
                                                    ></el-form-item
                                                >
                                            </el-col>
                                        </el-row>
                                        <el-row
                                            v-if="
                                                formData.state === 5
                                            "
                                        >
                                            <el-col :span="12">
                                                <el-form-item label="作废人：">
                                                    <span>{{
                                                        formData.nullifyCreator
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="作废原因："
                                                >
                                                    <span>{{
                                                        formData.nullifyReason
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row
                                            v-if="
                                                formData.state === 5
                                            "
                                        >
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="作废说明："
                                                >
                                                    <span>{{
                                                        formData.nullifyDescription
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="作废时间："
                                                >
                                                    <span>{{
                                                        formData.nullifyCreated
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                    </el-form>
                                </div>
                            </div>
                        </div>

                        <!-- ------------------------------------------------------------------------------------- -->
                    </div>

                    <!-- 验收明细 -->
                    <div id="receivingMaterialsCon" class="con">
                        <div class="tabs-title" id="receivingMaterials">
                            验收明细
                        </div>
                        <div class="e-table">
                            <!-- <div
                                class="top"
                                v-if="formData.redBillState != '3'"
                            >
                                <div class="left">
                                    <div>
                                        <el-button
                                            size="mini"
                                            class="btn-blue"
                                            @click="supplierNameClick"
                                            >选择物资</el-button
                                        >
                                        <el-button size="mini">删除</el-button>
                                    </div>
                                </div>
                            </div> -->
                            <div
                                class="errorMsg"
                                v-if="errorAcceptanceMsg.length > 0"
                            >
                                <span>
                                    {{ errorAcceptanceMsg.join(',') }}
                                </span>
                            </div>
                            <el-table
                                :data="acceptanceData"
                                ref='acceptanceTable'
                                border
                                style="width: 100%"
                                @cell-mouse-enter="cellMouseEnter"
                                @cell-mouse-leave="cellMouseLeave"
                                :row-class-name="tableRowClassName"
                                :cell-class-name="cellClsNm"
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                row-key="uuid"
                                :max-height="$store.state.tableHeight"
                                v-sortTable="{ 'tableData': acceptanceData, '_this': this, 'ref': 'acceptanceTable' }"
                            >

                                <el-table-column
                                    prop="materialClassName"
                                    label="物资类别"
                                    min-width="170"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialName"
                                    label="物资名称"
                                    min-width="130"
                                >
                                </el-table-column>
                                <el-table-column prop="spec" label="规格">
                                </el-table-column>
                                <el-table-column prop="texture" label="材质">
                                </el-table-column>
                                <el-table-column prop="unit" label="计量单位">
                                </el-table-column>
                                <el-table-column
                                    prop="warehouseName"
                                    label="仓库"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="noAcceptanceQuantity"
                                    label="未验收数量"
                                    width="100"
                                >
                                <template v-slot="{ row }">
                                        <span v-if="!row.children">{{
                                            +(+row.noAcceptanceQuantity -
                                            +row.acceptanceQuantity).toFixed(2)
                                        }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="验收数量" width="120" prop='acceptanceQuantity'>

                                </el-table-column>
                                <el-table-column
                                    prop="price"
                                    label="验收单价（元）"
                                    width="110"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="验收金额（元）"
                                    width="120"
                                    prop='acceptanceAmount'
                                >

                                </el-table-column>
                                <el-table-column
                                    prop="shareFreight"
                                    label="分摊服务费（元）"
                                    width="110"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="amortizationType"
                                    label="推销方式"
                                    width="110"
                                >

                                </el-table-column>
                                <el-table-column
                                    label="总摊销比例%"
                                    width="120"
                                    prop='amortizationRatio'
                                >

                                </el-table-column>
                                <el-table-column
                                    label="推销时间(月)"
                                    width="120"
                                    prop='amortizationDate'
                                >

                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <!-- 服务费用 -->
                    <div id="serviceChargeCon" class="con">
                        <div class="tabs-title" id="serviceCharge">
                            服务费用
                        </div>
                        <div class="e-table">
                            <!-- <div
                                class="top"
                                v-if="formData.redBillState != '3'"
                            >
                                <div class="left">
                                    <div>
                                        <el-button
                                            size="mini"
                                            class="btn-blue"
                                            @click="serviceFeeAdd"
                                            >新增行</el-button
                                        >
                                        <el-button size="mini">删除</el-button>
                                    </div>
                                </div>
                            </div> -->
                            <div
                                class="errorMsg"
                                v-if="errorServiceFeeMsg.length > 0"
                            >
                                <span>
                                    {{ errorServiceFeeMsg.join(',') }}
                                </span>
                            </div>
                            <el-table
                                :data="serviceFeeData"
                                ref='serviceFeeTable'
                                border
                                style="width: 100%"
                                @selection-change="serviceFeeSelect"
                                @cell-mouse-enter="cellMouseEnterF"
                                @cell-mouse-leave="cellMouseLeaveF"
                                :row-class-name="tableRowClassNameF"
                                :cell-class-name="cellClsNm"
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :max-height="$store.state.tableHeight"
                                v-sortTable="{ 'tableData': serviceFeeData, '_this': this, 'ref': 'serviceFeeTable' }"
                            >
                                <el-table-column type="selection" width="55">
                                </el-table-column>
                                <el-table-column
                                    label="合同编号"
                                    fixed
                                    min-width="150"
                                    prop='contractNp'
                                >

                                </el-table-column>
                                <el-table-column
                                    label="结算单位"
                                    fixed
                                    min-width="190"
                                    prop='settleOrgName'
                                >

                                </el-table-column>
                                <el-table-column label="清单名称" width="100" prop='detailedListName'>

                                </el-table-column>
                                <el-table-column label="数量" width="100" prop='quantity'>

                                </el-table-column>
                                <el-table-column
                                    prop="price"
                                    label="单价(元)"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column label="金额(元)" width="100" prop='amount'>

                                </el-table-column>
                                <el-table-column label="发票编号" width="130" prop='invoiceNo'>

                                </el-table-column>
                                <el-table-column label="税率%" width="130" prop='taxRate'>

                                </el-table-column>
                                <el-table-column label="税额（元）" width="130" prop='taxAmount'>

                                </el-table-column>
                                <el-table-column
                                    prop="totalPriceAndTax"
                                    label="税价合计（元）"
                                    width="130"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                    <!-- 附件信息 -->
                    <div id="accessoryCon" class="con">
                        <div class="tabs-title" id="accessory">附件信息</div>
                        <attach-comp
                            :relationId="billid"
                            bucketName="materialsettle"
                            v-if="objFlag.flag5"
                            :isView='true'
                        />
                        <div class="seize-a-seat" v-else>
                            <i class="el-icon-loading"></i>
                        </div>
                    </div>
                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <AcceptanceHistory
                            :billType="6081"
                            :billId="billid"
                            @historyTableHeight='historyTableHeight'
                            :url='url'
                        ></AcceptanceHistory>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons" v-if='!isview'>
            <!-- <el-button
                type="primary"
                style="background: #2e61d7"
                v-if="formData.state == 1 || formData.state == 9 || formData.state == 2"
                >打印</el-button
            > -->
            <el-button
                type="primary"
                style="background: #2e61d7"
                v-if="
                    formData.state === 2 &&
                    (formData.redBillState === '' ||
                        formData.redBillState === -1)
                "
                @click="redSingle"
                >冲红单</el-button
            >
            <exaButtons :auditState="auditState" @exas="exas" v-if='formData.state !== 5' :state='formData.state' :founderId='formData.founderId' :multiple="formData.state === 1 || formData.state === 2" :commandList='commandList'></exaButtons>

            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations, mapState } from 'vuex'
import { showLoading, hideLoading, openAppClient } from '@/utils/common'
import AttachComp from '@/components/common/attachIndex'
import request from '@/api/settlementManagement/acceptanceManagement/weeklyMaterialAcc'
import { getUuid } from '@/utils/common'
import AcceptanceHistory from '@/pages/materialsmanagement/checkAdmin/AcceptanceHistory'
import exaButtons from '@/components/common/exaButtons'
import { webprintReport, numToChinese } from '@/utils/common'

export default {
    components: {
        AttachComp,
        AcceptanceHistory,
        exaButtons
    },
    data () {
        return {
            tabsName: 'baseInfo',
            userName: '',
            acceptanceData: [], // 验收明细数据
            serviceFeeData: [], //服务费用数据
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            //表单数据
            formData: {
                billNo: '', //验收编号
                orgName: '', //所属机构
                businessTypeKey: '', //业务类型
                sourceNo: '', //源单编号
                supplierName: '', //供应商
                purchaserName: '', //采购人员
                purchasingUnitName: '', //采购单位
                acceptancerName: '', //验收人员
                acceptanceAmount: '', //验收金额
                acceptanceDate: '', //验收日期
                isAccepSettle: false, //验结一体
                transportationCost: '', //运输单位费用
                taxRate: '', //税率
                totalPriceAndTax: '', //税价合计
                taxAmount: '', //税额
                currency: '', //币种
                isSharing: '', //传财务共享
                baseCurAcceptanceAmount: '', //验收金额(本位币)
                baseCurName: '', //本位币
                settleNo: '', //结算编号
                redBillState: '',
                remarks: '', //备注
                state: 0, //状态
                acceptanceQuantity: 0,
                acceptancerId: '',
                baseCurId: '',
                baseCurExchangeRate: '',
                baseCurTaxAmount: 0,
                baseCurTotalAmount: 0,
                billId: '',
                currencyId: '',
                easId: '',
                founderId: '',
                founderName: '',
                gmtCreate: '',
                gmtModified: '',
                invoiceNo: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: '',
                orgId: '',
                purchaserId: '',
                purchasingUnitId: '',
                rmbAcceptanceAmount: 0,
                rmbId: '',
                rmbName: '',
                rmbRate: 0,
                rmbTaxAmount: 0,
                rmbTotalAmount: 0,
                settleId: '',
                sourceBillId: '',
                sourceId: '',
                sourceNumber: '',
                supplierId: '',
                workId: '',
                redBillId: '',
                redBillNo: '',
                approachCost: 0,
                baseAcceptanceAmount: 0,
                billSource: 0,
                businessTypeValue: '',
                hasInvoice: 0,
                parentId: ''
            },
            objFlag: {
                flag5: false
            },
            billid: '',
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转,
            businessTypeList: [
                {
                    key: '0',
                    value: '物资采购合同'
                },
                {
                    key: '1',
                    value: '临时需用计划(自购)'
                },
                {
                    key: '2',
                    value: '周材调拨'
                },
                {
                    key: '3',
                    value: '事实合同'
                },
            ],
            formDataRules: {
                businessTypeKey: [
                    {
                        required: true,
                        message: '请选择业务类型',
                        trigger: 'blur'
                    }
                ],
                supplierName: [
                    {
                        required: true,
                        message: '请选择供应商',
                        trigger: 'blur'
                    }
                ],
                sourceNo: [
                    {
                        required: true,
                        message: '请选择源单编号',
                        trigger: 'blur'
                    }
                ],
                purchaserName: [
                    {
                        required: true,
                        message: '请选择采购人员',
                        trigger: 'blur'
                    }
                ],
                acceptanceAmount: [
                    {
                        required: true,
                        message: '请输入验收金额',
                        trigger: 'blur'
                    }
                ],
                taxRate: [
                    { required: true, message: '请输入税率', trigger: 'blur' }
                ],
                taxAmount: [
                    { required: true, message: '请输入税额', trigger: 'blur' }
                ],
                totalPriceAndTax: [
                    { required: true, message: '请输入税价合计', trigger: 'blur' }
                ],
                transportationCost: [
                    { required: true, message: '请输入服务费用', trigger: 'blur' }
                ],
                currencyId: [
                    { required: true, message: '请选择币种', trigger: 'blur' }
                ],
                invoiceNo: [
                    {
                        required: true,
                        message: '请填写发票号',
                        trigger: 'blur'
                    }
                ],
                baseCurName: [
                    {
                        required: true,
                        message: '请选择本位币',
                        trigger: 'blur'
                    }
                ],
                baseCurExchangeRate: [
                    {
                        required: true,
                        message: '请填写本位币汇率',
                        trigger: 'blur'
                    }
                ]
            },
            isBatch: true,
            MouseEnterId: null,
            MouseEnterIdF: null,
            serviceFeeRow: {
                amount: 0,
                billId: '',
                changeType: 0,
                contractId: '',
                contractNp: '',
                detailedListName: '',
                dtlId: '',
                invoiceNo: '',
                price: 0,
                quantity: 0,
                settleOrgId: '',
                settleOrgName: '',
                taxAmount: 0,
                taxRate: 0,
                totalPriceAndTax: 0
            },
            billingUnitQuery: {
                businessUnitTypes: [],
                keyword: '',
                limit: 2,
                orgId: '',
                outerTypes: [],
                page: 1,
                states: [],
                type: []
            },
            auditState: {},
            auditParams: {
                // 审核
                billId: '',
                billType: 6081,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            },
            nullifyParams: {
                // 作废
                billId: this.$route.query.billid,
                billType: '6081',
                nullifyDescription: '',
                nullifyReason: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: ''
            },
            errorList: [], //控制导航栏感叹号的显示
            errorAcceptanceMsg: [], // 验收明细
            errorServiceFeeMsg: [], // 服务费用
            redBillStateStyle: {
                width: '300px',
                height: '30px',
                color: '#fff',
                backgroundColor: '',
                'text-align': 'center'
            },
            redFormData: null,
            jsdwData: {
                businessUnitTypes: [],
                keyword: '',
                limit: 10,
                orgId: '',
                outerTypes: [],
                page: 1,
                states: [],
                type: null
            },
            jsdwIds: null,
            isBaseCurRate: true,
            amortizationTypeList: [
                { key: 1, label: '周期摊销' },
                { key: 2, label: '产值摊销' }
            ],
            isRedSingle: false,
            historyData: [],
            url: '/turnover/audit/getAuditHistory',
            isview: false, // 如果是别的页面弹出此页面,需要隐藏下面的按钮
            commandList: [
                { key: 1, value: '周材验收单' },
                { key: 2, value: '周材采购服务费验收单' }
            ],
            serviceFeeList: []
        }
    },
    computed: {
        ...mapState({
            currencyForm: state => state.equip.equipData.currencyForm //币种
        }),
        //状态
        // statusLable () {
        //     return param => {
        //         const state = this.$store.state.settlementManagement.ysState
        //         const obj = state.find(x => x.value == param)
        //         return obj ? obj.label : ''
        //     }
        // },

        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 100 - this.lastConHeight
        },
        // 红单状态
        redBillStateFun () {
            let redState = ''
            switch (this.formData.redBillState) {
            case 0:
                redState = '冲销中'
                break
            case 1:
                redState = '冲销中'
                break
            case 2:
                redState = '已冲销'
                break
            case 3:
                redState = '红单'
                break
            }
            return redState
        }
    },
    watch: {
        'formData.isAccepSettle' () {
            // 如果验结一体未勾选,则需要清除发票号的提示信息
            if (!this.formData.isAccepSettle) {
                this.$refs.formDataRef.clearValidate('invoiceNo')
                this.formData.invoiceNo = ''
            }
        },
        // 本位币和币种一样的时候，值为1；不一样的时候，填写正数，不能为0，保留4位小数
        'formData.currency' (newData, oldData) {
            if (this.formData.currency == this.formData.baseCurName) {
                this.isBaseCurRate = true
                this.formData.baseCurExchangeRate = 1
            } else {
                this.isBaseCurRate = false
                if (oldData != '') {
                    this.formData.baseCurExchangeRate = null
                }
            }
        },

        'formData.redBillState' () {
            if (this.formData.redBillState == 3) {
                this.redBillStateStyle.backgroundColor = '#FF2300'
            } else if (
                this.formData.redBillState == 0 ||
                this.formData.redBillState == 1
            ) {
                this.redBillStateStyle.backgroundColor = '#FFA40D'
            } else if (this.formData.redBillState == 2) {
                this.redBillStateStyle.backgroundColor = 'rgb(153,153,153)'
            }
        },
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        }
    },
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.billid = this.$route.query.billid
        this.auditParams.billId = this.$route.query.billid
        if(this.$route.query.isview === 'true' || this.$route.query.isview === 'false') {
            this.isview = JSON.parse(this.$route.query.isview)
        }
        this.getAllData()
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = [
            'baseInfo',
            'receivingMaterials',
            'serviceCharge',
            'accessory',
            'auditHistory'
        ]
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop + 20
                    }
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 50 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    },
    methods: {
        ...mapMutations(['setPopConfirm', 'setAuditParams', 'setSelectedInfo']),
        //如果是新增后,直接跳转到编辑页的情况需要跳转到第二个标签
        scorllDtl () {
            if (this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        getAllData () {
            showLoading()
            Promise.all([
                this.getBasicData(), //进入页面就获取基本信息数据
                this.getAttach(), // 附件列表
                this.getUnitInfo() // 获取按钮状态
            ]).finally(() => {
                hideLoading()
            })
        },

        //获取基本信息数据
        async getBasicData () {
            let data = await request.getWeeklyMaterialBasicInfo(this.billid)
            this.redFormData = this._.cloneDeep(data)
            if (data.redBillState == 3) {
                // 如果是3,说明进入该单据是红单进入到编辑页
                data.currency = this.currencyForm.find(
                    x => x.value == data.currencyId
                ).label
                this.formData = data
                this.isRedSingle = true
            } else {
                this.formData = data
            }
            // 开启验收金额(元)的监听
            this.$watch('formData.acceptanceAmount', () => {
                // 税价合计 = 验收金额 + 税额
                this.formData.totalPriceAndTax =
                    +this.formData.acceptanceAmount + +this.formData.taxAmount
                // 验收金额(本位币) = 验收金额 * 本位币汇率
                this.formData.baseAcceptanceAmount =
                    +this.formData.acceptanceAmount *
                    +this.formData.baseCurExchangeRate
            })
            // 监听税额
            this.$watch('formData.taxAmount', () => {
                // 税价合计 = 验收金额+税额
                this.formData.totalPriceAndTax =
                    +this.formData.acceptanceAmount + +this.formData.taxAmount
            })
            await this.getAcceptanceList() // 验收明细表格数据
            await this.getServeList() // 服务费用表格数据
        },
        // 源单编号-跳转到 ...的详情页
        sourceNoClick () {
            let url = ''
            let name = ''
            switch(this.formData.businessTypeKey) {
            case '0':
                url = '/ctMaterialApplyShow'
                name = '物资采购合同查看页'
                break
            case '1':
                url = '/momentNeedPlanShow'
                name = '临时需用计划查看页'
                break
            case '2':
                url = '/revolveAllocationShow'
                name = '调拨单查看页'
                break
            }
            openAppClient(
                `${url}?billid=${this.formData.sourceId}&isview=${true}`,
                `${name}`
            )
        },
        // 结算编号-跳转到周材采购结算详情页
        settlementNoClick () {
            openAppClient(
                `/purchaseSettlementAcceptanceAndSettlement?isview=${true}&billid=${
                    this.formData.settleId
                }`,
                '查看周材采购结算'
            )
        },

        // 供方后面: 选择入库明细
        async supplierNameClick () {
            if (this.formData.businessTypeKey === '') {
                return this.clientPop('err', '请先选择业务类型')
            }
            try {
                let res = await request.getWarehousingList({
                    businessTypeKey: this.formData.businessTypeKey, //必传
                    parentId: '0'
                })
                // this.setSelectedInfo(res)
                // openAppClient('/showSelectedData', '选择结果')
                let data = res.find(item => item.parentId != 0)
                if (this.acceptanceData.length < 1 || !this.formData.supplierId) {
                    this.assignmentFun(data)
                    this.acceptanceData = this.acceptanceFun(res)
                } else if (this.formData.sourceNo != data.sourceNo) {
                    // 如果原有供应商和当前选择供应商不一致
                    this.clientPop(
                        'info',
                        '当前选择供应商或合同/计划与原有供应商或合同/计划不一致,若点击确定原有验收明细将被覆盖',
                        () => {
                            // 如果点击的确认,则处理数据格式,并把最新的数据赋值给验收明细数组
                            this.assignmentFun(data)
                            this.acceptanceData = this.acceptanceFun(res)
                        }
                    )
                } else if (this.formData.sourceNo == data.sourceNo) {
                    let newArr = this.acceptanceFun(res)
                    this.acceptanceData.forEach(item => {
                        newArr.forEach(itm => {
                            if (item.topClassId != itm.topClassId) {
                                // 遍历当前选择数组的每一项父级是否存在于原有数组中,如果没有,则直接添加
                                this.acceptanceData.push(itm)
                            } else if (item.topClassId == itm.topClassId) {
                                item.children.forEach(its => {
                                    itm.children.forEach(i => {
                                        if (its.materialId != i.materialId) {
                                            // 如果当前选择项的父级存在于原有数组中,但是没有当前遍历到的子项,则将这个子项添加于原有数组中的children中
                                            item.children.push(i)
                                        }
                                    })
                                })
                            }
                        })
                    })
                }
                this.acceptanceData.forEach(item => {
                    this.formData.acceptanceAmount = item.children.reduce((pre, c) => pre += (+c.acceptanceAmount || 0), 0).toFixed(2)
                })
            } catch (err) {
                alert(err.message)
            }
        },
        acceptanceFun (res) {
            const newArr = []
            let obj = {}
            res.forEach(item => {
                if (item.materialClassName) {
                    const topClassName = item.materialClassName.split('/')[0]
                    const topClassId = item.materialClassId.split('/')[0]
                    obj = {
                        topClassId,
                        topClassName,
                        customId: topClassId,
                        materialClassId: topClassId,
                        materialClassName: topClassName,
                        uuid: getUuid(),
                        totalAmount: null,
                        totalQuantity: null,
                        sourceId: item.sourceId,
                        children: []
                    }
                    if (newArr.length < 1) {
                        newArr.push(obj)
                    } else {
                        newArr.forEach(itm => {
                            if (itm.topClassId !== topClassId) {
                                newArr.push(obj)
                            }
                        })
                    }
                }
                newArr.forEach(its => {
                    its.children.push({
                        uuid: getUuid(),
                        customId: getUuid(),
                        acceptanceAmount: null, // 验收金额
                        acceptanceQuantity: item.acceptanceQuantity
                            ? item.acceptanceQuantity
                            : item.noAcceptanceQuantity, //已验收数量
                        billId: this.billid, //	验收ID
                        changeType: 1, //变更类型
                        dtlId: '', //验收明细ID
                        materialClassId: item.materialClassId
                            .split('/')
                            .slice(1, 3)
                            .join('/'), //物资类别id
                        materialClassName: item.materialClassName
                            .split('/')
                            .slice(1, 3)
                            .join('/'), // 物资类别名称
                        materialId: item.materialId, //物资id
                        materialName: item.materialName, //物资名称
                        noAcceptanceQuantity: item.noAcceptanceQuantity, // 未验收数量
                        price: null,
                        shareFreight: '', // 分摊运费
                        sourceDtlId: item.dtlId, //源单明细id
                        spec: item.spec, //规格型号
                        texture: item.texture, //材质
                        unit: item.unit, //计量单位
                        warehouseId: item.warehouseId, //仓库id
                        warehouseName: item.warehouseName,
                        amortizationDate: '', //摊销时间
                        amortizationRatio: null, // 摊销比例
                        amortizationType: null // 摊销方式
                    })
                    // 统计小计
                    const count = its.children.reduce(
                        (prev, c) => (prev += c.acceptanceAmount || 0),
                        0
                    ).toFixed(2)
                    its.materialName = `金额小计： ${count}`
                })
            })
            return newArr
        },
        async assignmentFun (data) {
            this.formData.supplierName = data.acceptOrgName // 供应商
            this.formData.supplierId = data.acceptOrgId // 供应商ID
            this.formData.purchaserName = data.purchaserName // 采购人员名称
            this.formData.purchaserId = data.purchaserId // 采购人员ID
            this.formData.sourceNo = data.sourceNo // 源单编号
            this.formData.sourceId = data.sourceId // 源单ID

            // 如果选择合同和周材调拨源单带入数据; 计划和事实合同类型，由用户下拉单选
            // // 如果选择的是物资采购合同,调合同的接口带入税率
            if (
                this.formData.businessTypeKey == 0 ||
                this.formData.businessTypeKey == 2
            ) {
                let data1 = await request.getcontractbasicInfo(data.sourceId)
                if (data1) {
                    this.formData.currency = data1.currencyName // 币种名称
                    this.formData.currencyId = data1.currencyId // 币种ID
                    this.formData.baseCurName = data1.baseCurName // 本位币名称
                    this.formData.baseCurId = data1.baseCurId // 本位币ID
                    this.formData.taxRate = data1.taxRate // 物资采购合同：带入合同税率。
                }
            }
        },

        // 税率只能输入0-100的数
        onInput0_100 (e) {
            this.$message.closeAll()
            if (e.target.value < 0 || e.target.value > 100) {
                this.$message.warning('只能输入[0,100]区间的数')
            }
            e.target.value =
                (e.target.value >= 0 &&
                    e.target.value <= 100 &&
                    e.target.value.match(/^\d{1,3}(\.\d*)?$/)[0]) ||
                null
        },
        // 本位币汇率不能为0
        baseCurExchangeRateBlur () {
            if (this.formData.baseCurExchangeRate == 0) {
                this.formData.baseCurExchangeRate = null
            }
            this.formData.baseCurAcceptanceAmount =
                +this.formData.acceptanceAmount *
                +this.formData.baseCurExchangeRate
        },
        // 当币种切换时,获取人民币汇率
        currencyChange (val) {
            this.formData.currency = this.currencyForm.find(
                x => x.value === val
            ).label //币种名称
        },
        // 业务类型切换时,获取中文名
        businessTypeKeyChange (val) {
            this.formData.businessTypeValue = this.businessTypeList.find(
                item => item.key == val
            ).value
            this.formData.supplierName = ''
            this.formData.supplierId = ''
            this.formData.purchaserName = ''
            this.formData.purchaserId = ''
            this.formData.sourceNo = ''
            this.formData.sourceId = ''
            this.formData.currency = ''
            this.formData.currencyId = ''
            // this.formData.baseCurName = ''
            // this.formData.baseCurId = ''
            this.formData.taxRate = ''
            this.formData.acceptanceAmount = ''
            this.acceptanceData.forEach(item => {
                item.children.forEach(i => {
                    i.changeType = -1
                })
                // let isParentRow = item.children.every(i => i.changeType == -1)
                // if(isParentRow) {
                //     this.acceptanceData.splice(index, 1)
                // }
            })

        },

        // ------------------------------验收明细---------------------------------------

        // 获取验收明细表格数据(弹窗好了过后最终需要调的接口)
        async getAcceptanceList () {
            let res = await request.getAcceptanceList(this.billid)
            if (!Array.isArray(res)) return
            res.forEach(item => {
                item.materialClassName = item.topClassName
                item.uuid = getUuid()
                item.children.forEach(i => {
                    i.uuid = i.dtlId
                })
                const count = item.children.reduce(
                    (prev, c) => (prev += c.acceptanceAmount || 0),
                    0
                ).toFixed(2)
                item.materialName = `金额小计： ${count}`
                item.children.forEach(i => {
                    if(i.amortizationType == 1) {
                        i.amortizationType = '周期摊销'
                    }else if(i.amortizationType == 2) {
                        i.amortizationType = '产值摊销'
                    }
                })

            })
            this.acceptanceData = res
        },

        // 监听验收数量
        acceptanceQuantityBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }

            if (
                row.noAcceptanceQuantity &&
                row.acceptanceQuantity > row.noAcceptanceQuantity
            ) {
                row.acceptanceQuantity = ''
                row.price = 0
            } else {
                if (!!row.acceptanceAmount && !!row.acceptanceQuantity) {
                    row.price = +row.acceptanceAmount / +row.acceptanceQuantity
                }
            }
        },

        // 监听验收金额
        acceptanceAmountBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            row.price = +row.acceptanceAmount / +row.acceptanceQuantity
            this.acceptanceData.forEach(item => {
                const count = item.children.reduce(
                    (prev, c) => (prev += +c.acceptanceAmount || 0),
                    0
                ).toFixed(2)
                item.materialName = `金额小计： ${count}`
                this.formData.acceptanceAmount = count
            })
        },
        // 监听总摊销比例和摊销时间
        amortizationRatioBlur (row) {
            if (!row.amortizationRatio) {
                row.amortizationRatio = ''
            }
            if (!row.amortizationDate) {
                row.amortizationDate = ''
            }
        },

        //删除验收明细
        acceptanceDelete (row) {
            row.changeType = -1
        },
        // 如果changeType是删除,则隐藏这一行
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.billId
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },

        // ---------------------------------服务明细---------------------------------
        // 点击新增行
        serviceFeeAdd () {
            this.serviceFeeData.push(this.serviceFeeRow)
        },

        // 获取服务费用表格数据
        async getServeList () {
            let res = await request.getServeList(this.billid)
            if (Array.isArray(res)) {
                this.serviceFeeData = res
            }
        },

        // 结算单位弹窗选择点击保存后
        async billingUnitDialog (row, index) {
            this.jsdwIds = row.settlementUnitId
            let res = await request.getBillingUnit(this.jsdwData, this.jsdwIds)
            // async getServeList () { // 弹窗好了,需删除这行
            //     let res = await request.getServeList(this.billingUnitQuery) // 弹窗好了,需删除这行
            let result = {
                amount: null,
                billId: this.billid,
                changeType: 1,
                contractId: '',
                contractNp: '',
                detailedListName: '',
                dtlId: '',
                invoiceNo: '',
                price: null,
                quantity: null,
                settleOrgId: res.id,
                settleOrgName: res.outerName,
                taxAmount: null,
                taxRate: null,
                totalPriceAndTax: null
            }
            this.serviceFeeData[index] = result
            this.formData.transportationCost = this.serviceFeeData.reduce(
                (pre, c) => (pre += +c.amount || 0),
                0
            ).toFixed(2)
        },

        // })
        // },

        // 合同选择弹窗
        //  选择合同的接口由胡腾提供,合同的数据是从 物资采购合同服务清单,物流运输类服务采购合同清单
        async contractDialog (row, index) {
            let contracted = {
                contractId: row.contractBillId,
                contractType: row.contractBillType || 0
            }
            let res = await request.getContract(
                { orgid: this.orgId },
                contracted
            )
            // openAppClient('/showSelectedData', '选择结果', function () {
            //     alert(res)
            // })
            let result
            // 如果选择的是合同并且合同下有清单,则需带入合同下的清单
            if (res.list && res.list.length > 0) {
                result = res.list.map(item => {
                    return {
                        amount: null,
                        billId: this.billid,
                        changeType: 1,
                        contractId: res.contractId,
                        contractNp: res.contractNumber,
                        detailedListName: item.name, // 清单名称
                        dtlId: '',
                        invoiceNo: '',
                        price: null,
                        quantity: item.quantity,
                        quantitys: item.quantity, // 这个字段是用于在修改数量时,不能大于合同数量的
                        settleOrgId: res.secondPartyId,
                        settleOrgName: res.secondPartyName,
                        taxAmount: null,
                        taxRate: res.taxRate,
                        totalPriceAndTax: null
                    }
                })
                this.serviceFeeData.splice(index, 1, ...result)
            } else {
                // 如果选择的合同没有清单
                result = {
                    amount: null,
                    billId: this.billid,
                    changeType: 1,
                    contractId: res.contractId,
                    contractNp: res.contractNumber,
                    detailedListName: '', //清单名称
                    dtlId: '',
                    invoiceNo: '',
                    price: null,
                    quantity: null,
                    settleOrgId: res.secondPartyId,
                    settleOrgName: res.secondPartyName,
                    taxAmount: null,
                    taxRate: res.taxRate,
                    totalPriceAndTax: null
                }
                this.serviceFeeData[index] = result
            }
            this.formData.transportationCost = this.serviceFeeData.reduce(
                (pre, c) => (pre += +c.amount || 0),
                0
            ).toFixed(2)
        },
        // 清单名称
        detailedListNameBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
        },
        // 数量变化时
        quantityBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            // // 不能超过合同数量
            if (row.quantitys) {
                if (row.quantity > row.quantitys) {
                    row.quantity = row.quantitys
                }
            }
            if (!!row.amount && !!row.quantity) {
                row.price = +row.amount / +row.quantity
            }
        },
        // 金额变化时
        amountBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            if (!!row.amount && !!row.quantity) {
                row.price = +row.amount / +row.quantity
            }
            if (!!row.amount && !!row.taxRate) {
                row.taxAmount = +row.amount * +row.taxRate
            }
            if (!!row.amount && !!row.taxAmount) {
                row.totalPriceAndTax = +row.amount + +row.taxAmount
            }
            this.formData.transportationCost = this.serviceFeeData.reduce(
                (pre, c) => (pre += +c.amount || 0),
                0
            ).toFixed(2)
        },
        // 发票编号变化时
        invoiceNoBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
        },
        // 税率变化时
        taxRateBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            if (!!row.amount && !!row.taxRate) {
                row.taxAmount = +row.amount * +row.taxRate
            }
            if (!!row.amount && !!row.taxAmount) {
                row.totalPriceAndTax = +row.amount + +row.taxAmount
            }
        },
        //税额变化时
        taxAmountBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            if (!!row.amount && !!row.taxAmount) {
                row.totalPriceAndTax = +row.amount + +row.taxAmount
            }
        },

        // 服务费用单条删除
        serviceFeeDelete (row) {
            row.changeType = -1
        },
        tableRowClassNameF ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
        cellMouseEnterF (row) {
            this.MouseEnterIdF = row.billId
        },
        cellMouseLeaveF () {
            this.MouseEnterIdF = 0
        },
        // 复选框选中的数据
        serviceFeeSelect (selection) {
            this.serviceFeeList = selection
        },

        // -------------------在点击下面几个按钮前,需要做前置判断-------------------------
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //清除错误标签
        clearError (name) {
            const index = this.errorList.findIndex(x => x === name)
            if (index !== -1) {
                this.errorList.splice(index, 1)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        // 设置验收明细有错误时在表格上面显示的错误信息
        setErrorAcceptanceMsg (msg) {
            let index = this.errorAcceptanceMsg.findIndex(x => x === msg)
            if (index === -1) {
                this.errorAcceptanceMsg.push(msg)
            }
        },
        // 设置服务费用有错误时在表格上面显示的错误信息
        setErrorServiceFeeMsg (msg) {
            let index = this.errorServiceFeeMsg.findIndex(x => x === msg)
            if (index === -1) {
                this.errorServiceFeeMsg.push(msg)
            }
        },
        // 点击左边的Tab标签
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //保存基本信息时需要检测的
        updateBaseInfo () {
            return new Promise((resolve, reject) => {
                this.$refs.formDataRef.validate(valid => {
                    if (valid) {
                        if (this.formData.redBillState == 3) {
                            this.redFormData.remarks = this.formData.remarks
                        }
                        // this.setSelectedInfo(this.formData)
                        // openAppClient('/showSelectedData', '选择结果')
                        request
                            .saveWeeklyMaterialBasicInfo(
                                this.formData.redBillState == 3
                                    ? this.redFormData
                                    : this.formData
                            )
                            .then(() => {
                                this.clearError('baseInfo')
                                resolve()
                            })
                            .catch(err => {
                                reject(err)
                                this.setError('baseInfo')
                            })
                    } else {
                        this.setError('baseInfo')
                        reject('基本信息错误')
                    }
                })
            })
        },
        // 保存验收明细时需要检测的
        saveAcceptance () {
            // this.setSelectedInfo(this.acceptanceData)
            // openAppClient('/showSelectedData', '选择结果')
            this.errorAcceptanceMsg = []
            return new Promise((resolve, reject) => {
                this.acceptanceData.forEach(its => {
                    its.children.forEach(item => {
                        !item.materialClassName
                            ? this.setErrorAcceptanceMsg('请填写物资类别')
                            : ''
                        !item.materialName
                            ? this.setErrorAcceptanceMsg('请填写物资名称')
                            : ''
                        !item.unit
                            ? this.setErrorAcceptanceMsg('请填写计量单位')
                            : ''
                        !item.warehouseName
                            ? this.setErrorAcceptanceMsg('请填写仓库')
                            : ''
                        !item.noAcceptanceQuantity
                            ? this.setErrorAcceptanceMsg('请填写未验收数量')
                            : ''
                        !item.acceptanceQuantity
                            ? this.setErrorAcceptanceMsg('请填写验收数量')
                            : ''
                        !item.price
                            ? this.setErrorAcceptanceMsg('请填写验收单价(元)')
                            : ''
                        !item.acceptanceAmount
                            ? this.setErrorAcceptanceMsg('请填写验收金额(元)')
                            : ''
                        !item.amortizationType
                            ? this.setErrorAcceptanceMsg('请选择摊销方式')
                            : ''
                        !item.amortizationRatio
                            ? this.setErrorAcceptanceMsg('请填写总摊销比例%')
                            : ''
                        !item.amortizationDate
                            ? this.setErrorAcceptanceMsg('请填写推销时间(月)')
                            : ''
                        !item.shareFreight
                            ? this.setErrorAcceptanceMsg(
                                '请填写分摊服务费用(元)'
                            )
                            : ''
                    })
                })
                if (this.errorAcceptanceMsg.length > 0) {
                    this.setError('receivingMaterials')
                    reject('验收明细错误')
                    return
                } else {
                    request
                        .saveAcceptanceData(this.acceptanceData)
                        .then(() => {
                            this.clearError('receivingMaterials')
                            resolve()
                        })
                        .catch(err => {
                            this.errorAcceptanceMsg[0] = err.message
                            this.setError('receivingMaterials')
                            reject(err)
                            // alert(err.message)
                        })
                }
            })
        },
        // 保存服务明细时需要检测的
        saveServiceFee () {
            this.errorServiceFeeMsg = []
            return new Promise((resolve, reject) => {
                // 如果是基本信息处验结一体勾选中，则服务费用明细中发票编号必填
                if (this.formData.isAccepSettle) {
                    this.serviceFeeData.every(item => {
                        if (!item.invoiceNo) {
                            return this.setErrorServiceFeeMsg('请填写发票编号')
                        }
                    })
                }
                // 检测必填项是否全部填写完毕
                this.serviceFeeData.forEach(item => {
                    !item.settleOrgName
                        ? this.setErrorServiceFeeMsg('请填写结算单位')
                        : ''
                    // !item.detailedListName
                    //     ? this.setErrorServiceFeeMsg('请填写清单名称')
                    //     : ''
                    // !item.quantity
                    //     ? this.setErrorServiceFeeMsg('请填写数量')
                    //     : ''
                    // !item.price
                    //     ? this.setErrorServiceFeeMsg('请填写单价(元)')
                    //     : ''
                    // !item.amount
                    //     ? this.setErrorServiceFeeMsg('请填写金额(元)')
                    //     : ''
                    // !item.totalPriceAndTax
                    //     ? this.setErrorServiceFeeMsg('请填写税价合计(元)')
                    //     : ''
                })
                if (this.errorServiceFeeMsg.length > 0) {
                    this.setError('serviceCharge')
                    reject('服务费用错误')
                    return
                } else {
                    // 如果必填项已全部填完,那么才发送保存服务费用的接口,如果报错依然需要定位到具体位置
                    request
                        .saveServiceFeeData(this.serviceFeeData)
                        .then(() => {
                            this.clearError('serviceCharge')
                            resolve()
                        })
                        .catch(err => {
                            this.errorServiceFeeMsg[0] = err.message
                            this.setError('serviceCharge')
                            reject(err)
                        })
                }
            })
        },
        // 保存所有数据
        saveAll () {
            showLoading()
            this.errorList = []
            Promise.all([
                this.updateBaseInfo(),
                this.saveAcceptance(),
                this.saveServiceFee()
            ])
                .then(() => {
                    hideLoading()
                    this.clientPop('suc', '保存成功')
                })
                .catch(() => {
                    this.scorllError()
                })
                .finally(() => {
                    hideLoading()
                })
        },
        // 提取提交审核的公共部分
        submitReviewFun () {
            showLoading()
            this.errorList = []
            Promise.all([
                this.updateBaseInfo(),
                this.saveAcceptance(),
                this.saveServiceFee()
            ])
                .then(() => {
                    request
                        .commitAudit(this.auditParams)
                        .then(() => {
                            this.clientPop('suc', '提交成功', this.handleClose)
                        })
                        .catch(() => {
                            this.scorllError()
                        })
                })
                .catch(() => {
                    this.scorllError()
                })
                .finally(() => {
                    hideLoading()
                })
        },
        // 提交审核
        submitReview () {
            if (this.formData.isAccepSettle) {
                this.clientPop(
                    'info',
                    '将生成一笔相同金额的周材采购结算单据。请确认执行操作!',
                    () => {
                        this.submitReviewFun()
                    }
                )
            } else {
                this.submitReviewFun()
            }
        },
        // 审核
        onAudit () {
            showLoading()
            this.setAuditParams(this.auditParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/exaDialog', '填写审核意见', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                showLoading()
                request
                    .audit(auditParams)
                    .then(() => {
                        this.clientPop('suc', '审核成功', this.handleClose)
                    })
                    .finally(() => {
                        hideLoading()
                    })
            }, null, null, null, 'small')
        },

        // 撤销审核
        undoAudit () {
            this.clientPop('info', '确定返回上一步操作吗?', () => {
                showLoading()
                request
                    .undoAudit(this.auditParams)
                    .then(() => {
                        this.clientPop('suc', '撤回成功', this.handleClose)
                    })
                    .finally(() => {
                        hideLoading()
                    })
            })
        },
        // 作废
        nullify () {
            this.setAuditParams(this.nullifyParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                showLoading()
                request
                    .nullify(auditParams)
                    .then(() => {
                        this.clientPop('suc', '作废成功', this.handleClose)
                    })
                    .finally(() => {
                        hideLoading()
                    })
            }, null, null, null, 'small')
        },
        // 删除
        deleteData () {
            this.clientPop(
                'info',
                '确定要删除吗？数据删除后不可恢复，请谨慎操作！',
                () => {
                    showLoading()
                    request
                        .deleteData(this.billid)
                        .then(() => {
                            this.clientPop('suc', '删除成功', this.handleClose)
                        })
                        .finally(() => {
                            hideLoading()
                        })
                }
            )
        },
        // 打印
        async print (value) {
            const printData = async ()=>{
                showLoading()
                try{
                    const  params =  {
                        'reportTitle': '', //报表名
                        'orgName': this.formData.orgName, //单据机构
                        'reportQRUri': '', //报表内容URI
                        'billNo': this.formData.billNo, //单据编码
                        'summaryInfoItems': [], // 基本信息
                        'tables': [] //表格
                    }
                    const reportTitle = this.commandList.find(item=>item.key == value)
                    params.reportTitle = reportTitle.value
                    let tableObj = {}
                    if(reportTitle.key === 1) {
                        tableObj = {
                            1: this.ReceivingRpt()
                        }
                    }else {
                        tableObj = {
                            1: this.ReceivingRpt(),
                            2: this.ServAcceptanceCertificate()
                        }
                    }
                    const tableData = tableObj[reportTitle.key]
                    params.summaryInfoItems = tableData.basicInfo
                    params.tables.push(tableData.tableList)
                    params.tables.push(await this.auditHst())
                    hideLoading()
                    return params
                }catch(err) {
                    console.log(err)
                    // this.clientPop('err', '打印失败')
                    hideLoading()
                }
            }
            const data = await printData()
            webprintReport(data)
        },
        // 验收单
        ReceivingRpt () {
            const basicInfo = []
            const data = this.formData
            const list = [
                ['供货单位', data.supplierName, false],
                ['附件', '    ' + '张', false],
                ['验收依据', data.sourceNo, false],
                ['验收日期', data.acceptanceDate, false],
                ['本期验收金额(元)', data.acceptanceAmount, false],
                ['税率(%)', data.taxRate + '%', false],
                ['可抵扣税额(元)', data.taxAmount, false],
                ['价税合计金额(元)', data.totalPriceAndTax, false],
                ['价税合计金额大写', numToChinese(Math.abs(data.totalPriceAndTax)), true],
                ['备注信息', data.remarks, true],
            ]
            list.forEach(item => {
                const obj = {
                    label: '标题',
                    value: '内容',
                    isFullRow: false, // 是否占整行
                }
                obj.label = item[0]
                obj.value = item[1]
                obj.isFullRow = item[2]
                basicInfo.push(obj)
            })
            // 表格数据
            let newArr = this._.cloneDeep(this.acceptanceData)
            let lastArr = []
            newArr.forEach(item => {
                lastArr.push(item)
                if(item.children.length > 0) {
                    lastArr.push(...item.children)
                }
            })
            const tableList = {
                'tableTitle': '验收明细',
                'tableContent': {
                    '物资类别': 'materialClassName',
                    '物资名称': 'materialName',
                    '规格': 'spec',
                    '材质': 'texture',
                    '单位': 'unit',
                    '验收数量': 'acceptanceQuantity',
                    '验收单价(元)': 'price',
                    '验收金额(元)': 'acceptanceAmount',
                },
                'tableData': lastArr, //表格数据
            }
            return { basicInfo, tableList }
        },
        // 服务费验收单
        ServAcceptanceCertificate () {
            if(this.serviceFeeData.length > 0) {
                if(this.serviceFeeList.length < 1) {
                    this.serviceFeeList = this._.cloneDeep(this.serviceFeeData)
                    return this.FmtData(this.serviceFeeList)
                }else {
                    return this.FmtData(this.serviceFeeList)
                }
            }else {
                this.clientPop('err', '服务费用无明细可打印')
                return
            }
        },
        // 格式数据
        FmtData (data) {
            // 是否相同结算单位
            const isTheSm = data.some(item =>data[0].settleOrgId !== item.settleOrgId)
            // 是否相同税率
            const isSmRt = data.some(item =>data[0].taxRate !== item.taxRate)
            if(isTheSm || isSmRt) {
                this.clientPop('err', '需选择相同结算单位和相同税率的数据,请先选择!')
                return
            }else {
                // 如果都是相同结算单位并且相同税率
                const obj = data.reduce((prev, c) => {
                    prev.amount += +(+c.amount).toFixed(2),
                    prev.totalPriceAndTax += +(+c.totalPriceAndTax).toFixed(2),
                    prev.taxAmount += +(+c.taxAmount).toFixed(2)
                    return prev
                }, { amount: 0, totalPriceAndTax: 0, taxAmount: 0, })
                obj.settlementUnitName = data[0].settlementUnitName
                obj.contractBillNo = data[0].contractBillNo
                obj.taxRate = data[0].taxRate
                return this.servPrnSelectFn(obj)
            }
        },
        servPrnSelectFn (obj) {
            const basicInfo = []
            const data = this.formData
            const list = [
                ['服务单位', obj.settleOrgName, false],
                ['附件', '    ' + '张', false],
                ['验收依据', obj.contractNp, false],
                ['验收日期', data.acceptanceDate, false],
                ['本期验收金额(元)', obj.amount, false],
                ['税率(%)', obj.taxRate + '%', false],
                ['可抵扣税额(元)', obj.taxAmount, false],
                ['价税合计金额(元)', obj.totalPriceAndTax, false],
                ['价税合计金额大写', numToChinese(Math.abs(obj.totalPriceAndTax)), true],
                ['备注信息', data.remarks, true],
            ]
            list.forEach(item => {
                const obj = {
                    label: '标题',
                    value: '内容',
                    isFullRow: false, // 是否占整行
                }
                obj.label = item[0]
                obj.value = item[1]
                obj.isFullRow = item[2]
                basicInfo.push(obj)
            })
            // 表格数据
            const tableList = {
                'tableTitle': '服务费明细',
                'tableContent': {
                    '结算单位': 'settleOrgName',
                    '清单名称': 'detailedListName',
                    '发票编号': 'invoiceNo',
                    '数量': 'quantity',
                    '单价(元)': 'price',
                    '金额': 'amount',
                    '税率': 'taxRate',
                    '税额': 'taxAmount',
                    '税额合计': 'totalPriceAndTax',
                },
                'tableData': this.serviceFeeList, //表格数据
            }
            return { basicInfo, tableList }
        },
        // 审核历史
        async auditHst () {
            //审核历史
            const historyTable  = await request.getAuditHistory(this.auditParams)
            const historyList = {
                'tableTitle': '审核历史',
                'tableContent': {
                    '审核级次': 'unitName',
                    '审核人': 'assignUser',
                    '审核人岗位': 'userTitle',
                    '通知时间': 'notifyTime',
                    '审核时间': 'completeTime',
                    '审核意见': 'opinion',
                },
                'tableData': historyTable, //表格数据
            }
            return historyList
        },
        // 点击冲红单
        async redSingle () {
            try {
                await request.isRedSingleFn(this.billid)
                this.$router.replace({
                    path: '/weeklyMaterialAccAdd',
                    query: { isRedSingle: '1', billid: this.billid }
                })
            }catch(err) {
                console.log(err)
            }
        },

        // ---------------------------下面按钮---------------------------
        // 获取按钮状态
        async getUnitInfo () {
            this.auditState = await request.getCurrentUnitInfo(
                this.auditParams
            )
        },

        // 点击下面几个不同的按钮做不同的操作
        exas (arg) {
            if (arg === 'submit') {
                this.saveAll() // 保存所有数据
            } else if (arg === 'submitCommit') {
                this.submitReview() // 保存并提交
            } else if (arg === 'audit') {
                this.onAudit() // 审核
            } else if (arg === 'undoAudit') {
                this.undoAudit() // 撤销审核
            } else if (arg === 'nullify') {
                this.nullify() // 作废
            } else if (arg === 'deleteData') {
                this.deleteData() // 删除
            } else if(arg.type === 'multiple') {
                this.print(arg.value) // 打印
            }
        },

        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('auditHistoryCon') && this.historyData.length > 0) {
                    const lastConHeight =
                        document.getElementById('auditHistoryCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        historyTableHeight (data) {
            this.historyData = data
        },

        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        //关闭
        handleClose () {
            hideLoading()
            this.$router.replace('/weeklyMaterialAccList')
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        showState (state) {
            const _state = this.$store.state.settlementManagement.ysState
            const obj = _state.find(x => x.value === Number(state))
            return obj.label
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}
::v-deep.el-table .warning-row {
    display: none;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
    width: 6px; // 横向滚动条
    height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 5px;
}

.el-tab-pane {
    margin-left: -10px;
}
::v-deep .el-table__fixed{
        height: 100% !important
}
</style>
